package com.csi.bumblebee.controller;

import com.csi.bumblebee.domain.user.MyJob;
import com.csi.bumblebee.domain.user.Student;
import com.csi.bumblebee.domain.vo.LoginVo;
import com.csi.bumblebee.domain.user.Company;
import com.csi.bumblebee.domain.user.Resume;
import com.csi.bumblebee.domain.util.MyResult;
import com.csi.bumblebee.domain.util.StateCode;
import com.csi.bumblebee.service.ResumeService;
import com.csi.bumblebee.service.impl.CompanyServiceImpl;
import com.csi.bumblebee.util.IdUtil;
import com.csi.bumblebee.util.JwtUtil;
import com.csi.bumblebee.util.UploadUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

import com.csi.bumblebee.service.JobService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.csi.bumblebee.domain.util.StateCode.*;

/**
 * 账号信息
 *
 * @author yeebs 孙伟俊
 */
@RestController
@RequestMapping("/company")
public class CompanyController {

    @Autowired
    private CompanyServiceImpl companyService;

    @Autowired
    private JobService jobService;

    /**
     * 根据id查询企业账号信息
     *
     * @param id company主键id
     * @return company对象
     */
    @GetMapping("/{id}")
    public MyResult<Company> findById(@PathVariable("id") String id) {
        MyResult<Company> myResult = new MyResult<>(FIND_FAILURE, "查询失败");
        Company company = companyService.findById(id);
        if (company != null) {
            myResult.setCode(FIND_SUCCESS);
            myResult.setData(company);
            myResult.setMessage("查询企业账号信息成功");
            return myResult;
        }
        return myResult;
    }


    /**
     * 增加岗位(岗位发布)
     *
     * @param job job对象
     * @return boolean值
     */
    @PutMapping("/job")
    @Transactional(rollbackFor = Exception.class)
    public MyResult<Boolean> add(@RequestBody MyJob job) {
        MyResult<Boolean> myResult = new MyResult<>(INSERT_FAILURE, "增加失败");
        if (jobService.add(job)) {
            myResult.setCode(INSERT_SUCCESS);
            myResult.setMessage("增加成功");
            myResult.setData(true);
        }
        return myResult;

    }

    @Autowired
    private ResumeService resumeService;

    /**
     * 根据条件查询简历
     * @param majorName
     * @param edLevel
     * @param seLevel
     * @return
     */
    @GetMapping("/resume/condition/list")
    public MyResult<List<Resume>> findByCondition(
            @RequestParam(name = "majorId", required = false) String majorId,
            @RequestParam(name = "educationBackgroundId", required = false) String educationBackgroundId,
            @RequestParam(name = "examResultId", required = false) String examResultId) {
        MyResult<List<Resume>> myResult = new MyResult<>(FIND_FAILURE, "查询失败");

        List<Resume> resumes = resumeService.findByCondition(majorId, educationBackgroundId, examResultId);

        if (resumes.size() != 0) {
            myResult.setCode(FIND_SUCCESS);
            myResult.setData(resumes);
            myResult.setMessage("条件查询成功");
            return myResult;
        }
        return myResult;
    }


    @Autowired
    private UploadUtils uploadUtils;

    /**
     * 登录
     */
    @PostMapping("/")
    public MyResult<LoginVo> login(@RequestBody Company company) {

        LoginVo login = companyService.login(company);

        String token = JwtUtil.createToken(company.getUsername(), "company", 1);

        MyResult<LoginVo> myResult = new MyResult<>();

        if(login == null) {

            myResult.setCode(StateCode.NOTINITAPPLICATION);
            myResult.setMessage("账号密码错误，或账号状态存在异常");
            return myResult;
        }

        else {
            login.setToken(token);
            if (login.getQualification() != null && !"".equals(login.getQualification())) {
                //是否通过申请
                myResult = companyService.isPassApplication(login);
            } else {
                myResult.setCode(StateCode.NOTINITAPPLICATION);
                myResult.setMessage("还未申请，请先申请");
            }
            return myResult;
        }
        //判断是否发起过申请

    }

    /**
     * 判断用户名是否重复
     */
    @PutMapping("/{userName}")
    public MyResult<String> judgeDuplicate(@PathVariable String userName) {

        MyResult<String> myResult = new MyResult<>();

        String isDuplicate = companyService.findDuplicate(userName);

        if ("".equals(isDuplicate)) {
            myResult.setCode(StateCode.NOTDUPLICATE);
        } else {
            myResult.setMessage("用户名重复");
            myResult.setCode(StateCode.DUPLICATE);
        }
        return myResult;
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    public MyResult<Company> register(@RequestBody Company company) {

        company.setId(IdUtil.getString(Company.PRE_NAME));
        int result = companyService.register(company);

        MyResult<Company> myResult = new MyResult<>();

        if (result > 0) {
            myResult.setCode(StateCode.INSERT_SUCCESS);
            myResult.setData(company);
        } else {
            myResult.setCode(StateCode.INSERT_FAILURE);
        }

        return myResult;
    }

    /**
     * 申请
     */
    @PostMapping("/application")
    public MyResult<Company> application(@RequestBody Company company) {
        return null;
    }

    /**
     * 验证token
     */
    @GetMapping("/authentication")
    public Boolean authentication(HttpServletRequest request) {
        String token = request.getHeader("token");

        System.out.println(token);

        return JwtUtil.parseToken(token);
    }

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public String upload(MultipartFile file) {
        String path = uploadUtils.uploadImage(file);
        System.out.println(path);
        return path;
    }

    @GetMapping("/test/{id}/{deleteId}")
    public void test(@PathVariable String id, @PathVariable String deleteId) {
        System.out.println(id + "=======" + deleteId);
    }

    @GetMapping("destroyedAccount/{id}")
    public MyResult<Boolean> destroyAccount(@PathVariable String id) {
        if(companyService.accountDestroy(id) == 1) {
            return new MyResult<Boolean>(UPDATE_SUCCESS, "成功");
        }
        return new MyResult<Boolean>(UPDATE_FAILURE, "失败");
    }

    /**
     * 修改企业账号状态
     *
     * @param company 企业对象（修改后）
     * @return 是结果载体，携带修改学生账号状态是否成功的data
     */
    @PostMapping("status")
    public MyResult<Boolean> updateStatus(@RequestBody Company company) {
        MyResult<Boolean> myResult = new MyResult<>(UPDATE_FAILURE, "修改账号状态失败");
        if (companyService.updateCompany(company)) {
            myResult.setCode(UPDATE_SUCCESS);
            myResult.setMessage("修改账号状态成功");
            myResult.setData(true);
        }
        return myResult;
    }
}
